import api from '@/apis/login'
import util from '@/util/message/message'
import {router} from '../router'
import store from '../store'
const actions = {
  login: async ({commit, dispatch}, {token, identity}) => {
    await commit('setToken', token)
    await commit('setUserIdentity', identity)
  },
  logout: async ({commit}) => {
    const result = await api.logout()
    if (result.code === 200) {
      commit('setUserIdentity', 0)
      commit('clearAdminInfo')
      commit('clearToken')
      commit('clearMenu')
      return 'success'
    } else {
      // eslint-disable-next-line no-undef
      util.errorMessage('服务端错误')
    }
  },
  getRouters: async ({commit, dispatch}) => {
    // 转换成普通数组
    let arrMenu = Object.assign([], store.state.menus).map(item => {
      return Object.assign({}, item)
    })
    const {menus} = store.state
    if (arrMenu.length > 0) {
      await dispatch('loadStore')
      console.log('无需发送路由表')
      let fmtRoutes = formatRoutes(JSON.parse(JSON.stringify(menus)))
      await fmtRoutes.forEach(item => {
        router.addRoute(item)
      })
    } else {
      console.log('发送请求拿路由表')
      const result = await api.loadRouters()
      if (result.code === 200) {
        // 深拷贝，拷贝一份数据进行操作，不会更改原来的数据
        await commit('setMenu', JSON.parse(JSON.stringify(result.data)))
        let fmtRoutes = formatRoutes(JSON.parse(JSON.stringify(result.data)))
        await fmtRoutes.forEach(item => {
          router.addRoute(item)
        })
      }
      await dispatch('pushEditor')
      // await router.push('/adminIndex')
    }
  },
  pushRoutes ({dispatch}) {
    if (window.sessionStorage.getItem('token')) {
      let fmtRoutes = formatRoutes(JSON.parse(JSON.stringify(store.state.menus)))
      fmtRoutes.forEach(item => {
        router.addRoute(item)
      })
      dispatch('pushEditor')
    }
  },
  loadStore: () => {
    store.replaceState(
      Object.assign(
        {},
        store.state,
        JSON.parse(window.sessionStorage.getItem('store'))
      )
    )
  },
  pushEditor () {
    router.addRoute('share', editor)
  }
}
const editor = {
  path: '/share/editor',
  name: 'editor',
  component: () => import('../components/common/Editor'),
  meta: {
    requiresAuth: true,
    showInbreadcrumb: true,
    menuName: '文章'
  }
}
const formatRoutes = (routes) => {
  let fmtRoutes = []
  routes.forEach(route => {
    if (route.children) {
      route.children = formatRoutes(route.children)
    }
    let fmtRoute = {
      path: route.path,
      component: () => import(`../${route.component}.vue`),
      name: route.name,
      menuName: route.menuName,
      icon: route.icon,
      // orderNum: route.orderNum,
      meta: {
        requiresAuth: true,
        menuName: route.menuName,
        showInbreadcrumb: true
      },
      children: route.children
    }
    fmtRoutes.push(fmtRoute)
  })
  return fmtRoutes
}
export default actions
